<template>
  <div 
    :class="[
      'bx-time-picker',
      'bx-glass',
      {
        'bx-time-picker--disabled': disabled,
        'bx-time-picker--focused': showPanel
      }
    ]"
    v-click-outside="handleClickOutside"
  >
    <BxInput
      :model-value="displayValue"
      :placeholder="placeholder"
      :disabled="disabled"
      :readonly="readonly"
      :size="size"
      @focus="handleFocus"
      @blur="handleBlur"
      @click="togglePanel"
      class="bx-time-picker__input"
    >
      <template #suffix>
        <BxIcon name="clock" class="bx-time-picker__icon" />
        <BxIcon 
          v-if="clearable && displayValue"
          name="x-circle"
          class="bx-time-picker__clear"
          @click.stop="handleClear"
        />
      </template>
    </BxInput>

    <div 
      v-if="showPanel"
      class="bx-time-picker__panel bx-glass"
    >
      <div class="bx-time-picker__columns">
        <!-- 小时 -->
        <ul class="bx-time-picker__column" ref="hourColumnRef">
          <li 
            v-for="h in hours"
            :key="`hour-${h}`"
            :class="[
              'bx-time-picker__item',
              { 'bx-time-picker__item--selected': selectedHour === h }
            ]"
            @click="selectHour(h)"
          >
            {{ String(h).padStart(2, '0') }}
          </li>
        </ul>

        <!-- 分钟 -->
        <ul class="bx-time-picker__column" ref="minuteColumnRef">
          <li 
            v-for="m in minutes"
            :key="`minute-${m}`"
            :class="[
              'bx-time-picker__item',
              { 'bx-time-picker__item--selected': selectedMinute === m }
            ]"
            @click="selectMinute(m)"
          >
            {{ String(m).padStart(2, '0') }}
          </li>
        </ul>

        <!-- 秒 -->
        <ul v-if="showSecond" class="bx-time-picker__column" ref="secondColumnRef">
          <li 
            v-for="s in seconds"
            :key="`second-${s}`"
            :class="[
              'bx-time-picker__item',
              { 'bx-time-picker__item--selected': selectedSecond === s }
            ]"
            @click="selectSecond(s)"
          >
            {{ String(s).padStart(2, '0') }}
          </li>
        </ul>
      </div>
      
      <div class="bx-time-picker__footer">
        <BxButton variant="text" size="small" @click="selectNow">此刻</BxButton>
        <BxButton type="primary" size="small" @click="confirmSelection">确定</BxButton>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch, nextTick } from 'vue'
import BxInput from '../input/BxInput.vue'
import BxIcon from '../basic/BxIcon.vue'
import BxButton from '../basic/BxButton.vue'

export default {
  name: 'BxTimePicker',
  components: {
    BxInput,
    BxIcon,
    BxButton
  },
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择时间'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    readonly: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: 'medium',
      validator: (value) => ['small', 'medium', 'large'].includes(value)
    },
    format: {
      type: String,
      default: 'HH:mm:ss'
    },
    showSecond: {
      type: Boolean,
      default: true
    }
  },
  emits: ['update:modelValue', 'change', 'focus', 'blur'],
  directives: {
    clickOutside: {
      mounted(el, binding) {
        el.__clickOutsideHandler__ = (event) => {
          if (!(el === event.target || el.contains(event.target))) {
            binding.value(event)
          }
        }
        document.addEventListener('click', el.__clickOutsideHandler__)
      },
      unmounted(el) {
        document.removeEventListener('click', el.__clickOutsideHandler__)
      }
    }
  },
  setup(props, { emit }) {
    const showPanel = ref(false)
    const selectedHour = ref(0)
    const selectedMinute = ref(0)
    const selectedSecond = ref(0)

    const hourColumnRef = ref(null)
    const minuteColumnRef = ref(null)
    const secondColumnRef = ref(null)

    const hours = computed(() => Array.from({ length: 24 }, (_, i) => i))
    const minutes = computed(() => Array.from({ length: 60 }, (_, i) => i))
    const seconds = computed(() => Array.from({ length: 60 }, (_, i) => i))

    const displayValue = computed(() => {
      if (!props.modelValue) return ''
      const [h, m, s] = props.modelValue.split(':').map(Number)
      let formatted = props.format
      formatted = formatted.replace(/HH/g, String(h).padStart(2, '0'))
      formatted = formatted.replace(/mm/g, String(m).padStart(2, '0'))
      formatted = formatted.replace(/ss/g, String(s || 0).padStart(2, '0'))
      return formatted
    })

    const parseTime = (timeStr) => {
      if (!timeStr) return null
      const [h, m, s] = timeStr.split(':').map(Number)
      return { h: h || 0, m: m || 0, s: s || 0 }
    }

    const formatTime = (h, m, s) => {
      let formatted = props.format
      formatted = formatted.replace(/HH/g, String(h).padStart(2, '0'))
      formatted = formatted.replace(/mm/g, String(m).padStart(2, '0'))
      formatted = formatted.replace(/ss/g, String(s).padStart(2, '0'))
      return formatted
    }

    const togglePanel = () => {
      if (props.disabled) return
      showPanel.value = !showPanel.value
      if (showPanel.value) {
        const parsed = parseTime(props.modelValue)
        if (parsed) {
          selectedHour.value = parsed.h
          selectedMinute.value = parsed.m
          selectedSecond.value = parsed.s
        } else {
          const now = new Date()
          selectedHour.value = now.getHours()
          selectedMinute.value = now.getMinutes()
          selectedSecond.value = now.getSeconds()
        }
        nextTick(() => {
          scrollToSelected()
        })
      }
    }

    const handleClickOutside = () => {
      showPanel.value = false
    }

    const handleFocus = (event) => {
      emit('focus', event)
    }

    const handleBlur = (event) => {
      emit('blur', event)
    }

    const selectHour = (h) => {
      selectedHour.value = h
    }

    const selectMinute = (m) => {
      selectedMinute.value = m
    }

    const selectSecond = (s) => {
      selectedSecond.value = s
    }

    const selectNow = () => {
      const now = new Date()
      selectedHour.value = now.getHours()
      selectedMinute.value = now.getMinutes()
      selectedSecond.value = now.getSeconds()
      nextTick(() => {
        scrollToSelected()
      })
    }

    const confirmSelection = () => {
      const time = formatTime(selectedHour.value, selectedMinute.value, selectedSecond.value)
      emit('update:modelValue', time)
      emit('change', time)
      showPanel.value = false
    }

    const handleClear = () => {
      emit('update:modelValue', '')
      emit('change', '')
    }

    const scrollToSelected = () => {
      const itemHeight = 32 // 每个选项的高度
      if (hourColumnRef.value) {
        hourColumnRef.value.scrollTop = selectedHour.value * itemHeight
      }
      if (minuteColumnRef.value) {
        minuteColumnRef.value.scrollTop = selectedMinute.value * itemHeight
      }
      if (secondColumnRef.value && props.showSecond) {
        secondColumnRef.value.scrollTop = selectedSecond.value * itemHeight
      }
    }

    watch(() => props.modelValue, (newVal) => {
      if (!showPanel.value) {
        const parsed = parseTime(newVal)
        if (parsed) {
          selectedHour.value = parsed.h
          selectedMinute.value = parsed.m
          selectedSecond.value = parsed.s
        }
      }
    })

    return {
      showPanel,
      selectedHour,
      selectedMinute,
      selectedSecond,
      hourColumnRef,
      minuteColumnRef,
      secondColumnRef,
      hours,
      minutes,
      seconds,
      displayValue,
      togglePanel,
      handleClickOutside,
      handleFocus,
      handleBlur,
      selectHour,
      selectMinute,
      selectSecond,
      selectNow,
      confirmSelection,
      handleClear
    }
  }
}
</script>

<style scoped>
.bx-time-picker {
  position: relative;
  display: inline-block;
  font-family: var(--bx-font-family);
}

.bx-time-picker__input {
  cursor: pointer;
}

.bx-time-picker__icon {
  font-size: 16px;
  color: var(--bx-text-secondary);
}

.bx-time-picker__clear {
  font-size: 14px;
  color: var(--bx-text-tertiary);
  cursor: pointer;
  margin-left: 8px;
}

.bx-time-picker__clear:hover {
  color: var(--bx-text-primary);
}

.bx-time-picker__panel {
  position: absolute;
  top: calc(100% + 8px);
  left: 0;
  width: 200px; /* 3列 * 60px/列 + 20px padding */
  border: 1px solid var(--bx-glass-border);
  border-radius: var(--bx-radius-medium);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  animation: bx-fade-in-up 0.2s ease-out;
  padding: 16px;
}

.bx-time-picker__columns {
  display: flex;
  justify-content: center;
  height: 200px;
  overflow: hidden;
  border: 1px solid var(--bx-glass-border);
  border-radius: var(--bx-radius-small);
  background: rgba(255, 255, 255, 0.05);
}

.bx-time-picker__column {
  flex: 1;
  list-style: none;
  padding: 0;
  margin: 0;
  overflow-y: scroll;
  text-align: center;
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}

.bx-time-picker__column::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera*/
}

.bx-time-picker__column + .bx-time-picker__column {
  border-left: 1px solid var(--bx-glass-border);
}

.bx-time-picker__item {
  padding: 8px 0;
  cursor: pointer;
  color: var(--bx-text-primary);
  transition: background-color var(--bx-transition-fast);
}

.bx-time-picker__item:hover {
  background: var(--bx-glass-bg-hover);
}

.bx-time-picker__item--selected {
  background: rgba(0, 122, 255, 0.8);
  color: #fff;
}

.bx-time-picker__footer {
  display: flex;
  justify-content: space-between;
  margin-top: 16px;
  border-top: 1px solid var(--bx-glass-border);
  padding-top: 12px;
}

@keyframes bx-fade-in-up {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .bx-time-picker {
    width: 100%;
  }
  
  .bx-time-picker__panel {
    width: 100%;
    left: 0;
    right: 0;
  }
}
</style>

